#!/usr/bin/env python
# Create: 2018/8/15
__author__ = '749B'

from django.forms import ModelForm
from django.core.exceptions import ValidationError


def create_model_form(admin_obj):
    """动态生成ModelForm"""
    class Meta:
        model = admin_obj.model
        fields = '__all__'

    def __new__(cls, *args, **kwargs):
        # cls.base_fields['qq'].widget.attrs['class'] = 'form-control'  # 指定某一个是这么来加的
        # 下面是要动态的把所有字段都加上
        # print(cls.base_fields)  # 先看看，这是一个序字典OrderedDict
        for field_name, field_obj in cls.base_fields.items():
            field_obj.widget.attrs['class'] = 'form-control'
            # 只读字段，为输入框设置readonly属性，禁止修改
            # bootstrap的disabled是禁用状态，禁止交互，也禁止鼠标动作，关键是还不会提交
            # bootstrap的readonly是禁用状态，禁止修改，但保留鼠标状态，也能提交原来的内容
            if field_name in admin_obj.readonly_fields:
                field_obj.widget.attrs['readonly'] = True
        return ModelForm.__new__(cls)

    def clean(self):
        for field in admin_obj.readonly_fields:
            default_value = getattr(self.instance, field)
            cleaned_value = self.cleaned_data.get(field)
            if default_value != cleaned_value:
                self.add_error(field, ValidationError("只读字段不能修改", code='readonly'))
            return self.cleaned_data

    # 这里先写个字典，下面再引用字典。之后这个类要添加什么方法都在这个字典里写
    # 这里的成员会被继承的属性覆盖掉
    members = {'Meta': Meta, '__new__': __new__, 'clean': clean}
    # 左边是类名
    # 右边的参数：类的类型名字，继承哪些基类，类的所有成员
    dynamic_model_form = type('DynamicModelForm', (ModelForm,), members)
    return dynamic_model_form

